<?php

namespace Logic;

class Product {

    const TABLE_PRODUCT = 'product';

    /**
     * 新增商品记录
     */
    public static function insert($param = []) {
        $ret = \Db::instance()->insert(self::TABLE_PRODUCT, $param);
        if (!$ret) {
            return false;
        }

        return $lastInsertId = $ret;
    }

    /**
     * 更新商品记录
     */
    public static function update($param = [], $productId = 0) {
        $where = "`product_id` = '$productId'";
        return \Db::instance()->updateByWhere(self::TABLE_PRODUCT, $param, $where);
    }

    /**
     * 清理商品记录
     */
    public static function delete($productId = 0) {
        if ($productId) {
            $where = "`product_id` = '$productId'";
            \Db::instance()->execute("delete from " . self::TABLE_PRODUCT . " where $where");
        }
    }

    /**
     * 计算红包, 到手价等信息
     */
    public static function getMore($zk_price = 0, $commission_rate = 0, $amount = 0) {
        // 店家返佣
        $income = ($zk_price - $amount) * $commission_rate * 0.0001;

        // 红包
        $red_packet = $income * \Config\System::$site['rmRate'];

        // 实购价
        $final_price = $zk_price - $amount - $red_packet;

        return [
            'zk_final_price' => $zk_price,
            'commission_rate' => $commission_rate,
            'red_packet' => sprintf("%01.2f", $red_packet),
            'amount' => $amount,
            'final_price' => sprintf("%01.2f", $final_price),
        ];
    }

    /**
     * 查询商品列表
     */
    public static function getProductList($where = "1=1", $order = 'id desc', $limit = 20, $page = 1, $more = 1, $type = '') {
        $return = [
            'dataList' => [],
            'nowPage' => $page,
        ];

        // 查询缓存
        if (!$more && $type && $page) {
            $file = CACHE_PATH . $type . '/' . $page . '.dat';
            if (is_file($file)) {
                $ret = file_get_contents($file);
                $data = json_decode($ret, true);
                if ($data) {
                    $return['dataList'] = $data;
                    return $return;
                }
            }
        }

        $page = $page ? $page : 1;
        $offset = ($page - 1) * $limit;
        $sql = "select `product_id`,`pict_url`,`title`,`commission_rate`,`coupon_id`,`coupon_share_url`,`zk_final_price`,`amount`,`red_packet`,`final_price`,`volume`,`item_description`,`click_url` from product where $where order by $order limit $limit offset $offset";
        $dataList = \Db::instance()->getList($sql);

        foreach ($dataList as $k => $d) {
            $product_id = $d['product_id'];
            $coupon_share_url = $d['coupon_share_url'];
            $click_url = $d['click_url'];
            $amount = $d['amount'];
            $red_packet = $d['red_packet'];

            $tmp = [
                $amount,
                $coupon_share_url ? $coupon_share_url : $click_url,
                $red_packet,
            ];

            $dataList[$k]['ext'] = \Common::deflate_data(implode('-', $tmp));
        }

        $return = [
            'dataList' => $dataList,
            'nowPage' => $page,
        ];

        return $return;
    }

    /**
     * 查询商品信息(DB)
     */
    public static function getProductInfo($product_id = 0) {
        $where = "`product_id` = '$product_id'";
        $sql = "select `product_id`,`pict_url`,`title`,`commission_rate`,`coupon_id`,`coupon_share_url`,`zk_final_price`,`amount`,`red_packet`,`final_price`,`volume`,`item_description`,`click_url` from product where $where";
        return \Db::instance()->getRow($sql);
    }

    /**
     * 查询商品详情
     */
    public static function getItemInfo($product_id = 0, $e = '', $type = 'item', $inviteid = '') {
        $result = \Logic\TaoApi::getDetails([$product_id]);
        if (!isset($result[$product_id])) {
            \Common::error('抱歉，未获取到商品信息。请刷新页面或点击下方刷新按钮。如果重试多次，仍旧如此，则此商品可能已下架');
        }

        $product_info = $result[$product_id];

        $ext = explode('-', \Common::inflate_data($e));

        $amount = $ext[0];
        $tg_url = $ext[1];
        $red_packet = $ext[2];

        $vid = \Common::getCookie('openid');
        $item_url = $vid ? \Config\System::$site['host'] . "item/{$product_id}?e={$e}&vid={$vid}" : \Config\System::$site['host'] . "item/{$product_id}?e={$e}";
        $product_info['item_url'] = $item_url;

        $product_info['short_url'] = '';
        $short_url = \Common::getShortUrl($item_url);
        if (!$short_url) {
            \Common::error("短网址生成失败，请刷新页面重试");
        }
        $product_info['short_url'] = $short_url;

        $product_info['tg_url'] = $tg_url;
        $product_info['amount'] = $amount;
        $product_info['red_packet'] = $red_packet;
        $product_info['final_price'] = $product_info['zk_final_price'] - $amount - $red_packet;
        $product_info['taocode'] = '';

        // 商品推荐理由
        $row = \Db::instance()->getRow("select `item_description` from `product` where `product_id`='$product_id'");
        $product_info['item_description'] = $row ? $row['item_description'] : '';

        if ($type == 'item') {
            $taocode = \Logic\TaoApi::createTbkTaocode($product_info['title'], $tg_url, $product_info['pict_url']);
            if (!$taocode) {
                exit('淘口令生成失败，请稍后重试');
            }
            $product_info['taocode'] = $taocode;
        }

        $note = static::formatItemInfo($product_info, $type);
        $product_info['note'] = $note;
        return $product_info;
    }

    /**
     * 格式化商品详情
     */
    private static function formatItemInfo($product_info = [], $type = 'item') {
        $string = $product_info['title'] . '<br>';

        if ($product_info['item_description']) {
            $string .= '<span class="red">' . $product_info['item_description'] . '</span><br>';
        }

        $string .= '<span class="font-gray">----------------------</span><br>';

        $string .= '★月销 <span class="red bigfont">' . \Common::format_volume($product_info['volume']) . '</span> 件<br>';

        $amount = $product_info['amount'];
        $red_packet = $product_info['red_packet'];
        $final_price = sprintf("%01.2f", $product_info['zk_final_price'] - $amount - $red_packet);

        $string .= "★现价<span class='delete-line bigfont'>{$product_info['zk_final_price']}元</span>, 到手<span class='red bigfont'>{$final_price}元</span><br>";

        $save = \Common::getShengString($amount, $red_packet);
        if ($save) {
            $string .= $save . '<br>';
        }

        if ($type == 'item') {
            $string .= "查看链接{$product_info['short_url']}<br>";
            $string .= "查看口令{$product_info['taocode']}<br>";
            //$string .= "{$product_info['item_url']}<br>";
        }

        $string .= '<span class="font-gray">----------------------</span><br>';

        if ($type == 'share') {
            $string .= "淘宝（天猫）购物, 买前领券省钱, <br>买后收货再领红包, 省了又省。";
        }

        return $string;
    }

    /**
     * 清理click_url
     */
    public static function cleanClickUrl($click_url = '') {
        $click_url = strpos($click_url, 'http') === false ? 'https:' . $click_url : $click_url;
        $t = parse_url($click_url);

        if (!isset($t['scheme']) || !isset($t['query']) || !isset($t['host']) || !isset($t['path'])) {
            return '';
        }

        $query = explode('&', $t['query'])[0];
        $return = $t['scheme'] . '://' . $t['host'] . $t['path'] . '?' . $query;
        return $return;
    }

    /**
     * 缓存商品列表数据
     */
    public static function cacheProductList($type = '', $where = '', $shuffle = true, $order = '') {
        $dir = CACHE_PATH . $type;
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }

        // 清除旧的文件
        for ($i = 1; $i <= 20; $i++) {
            $file = $dir . '/1.dat';
            if (is_file($file)) {
                unlink($file);
            }
        }

        // 取200条数据
        $order = $order ? $order : "`uptime` desc";
        $limit = $shuffle ? 500 : 400;
        $rs = static::getProductList($where, $order, $limit, 1);
        if (!$rs['dataList']) {
            return;
        }

        // 打乱数组的顺序
        $dataList = $rs['dataList'];
        if ($shuffle) {
            shuffle($dataList);
        }

        $count = count($dataList);
        if ($count > 400) {
            $tmp = array_slice($dataList, 0, 400);
            $dataList = $tmp;
        }

        $size = 20;
        $chunk = array_chunk($dataList, $size);

        foreach ($chunk as $k => $c) {
            $num = $k + 1;
            $data = json_encode($c);
            $cache_file = $dir . '/' . $num . '.dat';
            file_put_contents($cache_file, $data);
        }
    }

    /**
     * 商品加入黑名单
     */
    public static function addBlack($product_id = 0) {
        if ($product_id) {
            $param = ['product_id' => $product_id];
            \Db::instance()->insert('blacklist', $param);
        }
    }

    /**
     * 详情页是否跳转到微信授权页面
     * @param string $type 类型item or search
     * @param string $product_id 商品id
     * @param string $ext 商品扩展信息
     * @param string $role 访问者权限
     * @param string $co 访问来自
     * @param string $goto_url 跳转链接
     * @param string $getinviteid 邀请人openid
     */
    public static function itemGoToWx($type = 'item', $product_id = 0, $ext = '', $role = '', $co = '', $goto_url = '', $getinviteid = '') {
        // 参数为空, 直接跳过
        if ($type == 'item' && (!$product_id || !$ext)) {
            return;
        }

        if ($co) {
            return;
        }

        $isWx = \Common::isWx();
        // 管理员非微信客户端访问, 直接跳过
        if (($role == 'super' || $role == 'admin') && !$isWx) {
            return;
        }

        // 获取cookie信息
        $openid = \Common::getCookie('openid');
        $tc = \Common::getCookie('wx_user');
        $tarr = $tc ? json_decode(stripslashes($tc), true) : [];
        $wx_user = $tarr ? $tarr : [];
        $inviteid = \Common::getCookie('inviteid');

        // 用户微信账号信息不为空, 直接跳过
        if (!$getinviteid && !$inviteid && $openid && $wx_user && isset($wx_user['nickname']) && isset($wx_user['id']) && isset($wx_user['role']) && isset($wx_user['inviter'])) {
            return;
        }

        if ($openid && $getinviteid && $openid == $getinviteid && $wx_user) {
            return;
        }

        if ($openid && $inviteid && $openid == $inviteid && $wx_user) {
            return;
        }

        if ($goto_url) {
            // 如果有跳转链接直接去跳转链接
            $last_item = $goto_url . '?';
        } else {
            $last_item = 'my?';
            if ($type == 'item') {
                $last_item = "item/{$product_id}?e={$ext}";
            }
            if ($type == 'search') {
                $last_item = "search?";
            }
            if ($type == 'myindex') {
                $last_item = "my/index?";
            }
            if ($type == 'myorder') {
                $last_item = "my/order?";
            }
            if ($type == 'mypacket') {
                $last_item = "my/packet?";
            }
            if ($type == 'invite') {
                // 邀请有奖
                $last_item = "index/invite?";
            }
            if ($type == 'myinvite') {
                // 我的邀请好友
                $last_item = "my/invite?";
            }
            if ($type == 'invitepacket') {
                // 我的邀请红包
                $last_item = "my/invitepacket?";
            }
        }
        \Common::setCookie('last_item', $last_item, 3600);

        // 页面跳转
        $local_url = $getinviteid ? \Config\System::$site['host'] . 'index/itemgo?getinviteid=' . $getinviteid : \Config\System::$site['host'] . 'index/itemgo';
        $jump_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?'
                . 'appid=' . \Config\System::$site['wx']['appId']
                . '&redirect_uri=' . urlencode($local_url)
                . '&response_type=code&scope=snsapi_userinfo&state=1001#wechat_redirect';

        \Common::redirect($jump_url);
    }

    /**
     * 格式化user_item列表
     */
    public static function formatUserItem($data_list = []) {
        if (!$data_list) {
            return [];
        }

        $product_ids = array_column($data_list, 'product_id');
        $open_ids = array_column($data_list, 'openid');

        $details = \Logic\TaoApi::getDetails($product_ids);
        $uinfo = [];

        if ($open_ids) {
            $where = "`openid` in ('" . implode("','", $open_ids) . "')";
            $sql = "select `openid`,`nickname` from `wx_user` where $where";
            $uinfo = \Db::instance()->getList($sql, 'openid');
        }

        $return = [];
        foreach ($data_list as $k => $d) {
            $product_id = $d['product_id'];
            if (!isset($details[$product_id])) {
                continue;
            }
            $openid = $d['openid'];
            $return[$k] = $d;
            $return[$k]['pict_url'] = isset($details[$product_id]) ? $details[$product_id]['pict_url'] : '';
            $return[$k]['title'] = isset($details[$product_id]) ? $details[$product_id]['title'] : '';
            $return[$k]['volume'] = isset($details[$product_id]) ? $details[$product_id]['volume'] : '';
            $return[$k]['zk_price'] = isset($details[$product_id]) ? $details[$product_id]['zk_final_price'] : '';
            $return[$k]['nickname'] = isset($uinfo[$openid]) ? $uinfo[$openid]['nickname'] : '';
        }

        return $return;
    }

}
